import { createStore } from 'redux'
import langCN from './languages/langCN'
import langEN from './languages/langEN'

if (!window.pc) {
  window.pc = function() {
    return 0
  }
}

const SISSTIONKEY = 'front0'
let save = state => {
  state = {
    ...state,
    ui: {
      ...defaultState.ui
    }
  }
  window.localStorage[SISSTIONKEY] = JSON.stringify(state)
}
let load = () => {
  if (window.localStorage[SISSTIONKEY]) {
    return JSON.parse(window.localStorage[SISSTIONKEY])
  } else {
    return defaultState
  }
}

let defaultState = {
  user: { token: null },
  ui: { pc: window.pc() },
  lang: {
    ...langCN
  }
}

let dispatch = (state = defaultState, action) => {
  switch (action.type) {
    case 'clean':
      state = { ...defaultState }
      save(state)
      return state
    case 'save':
      save(state)
      return state
    case 'load':
      state = load()
      return state
    case 'lang':
      if (action.lang === 'CN') {
        state = {
          ...state,
          lang: {
            ...langCN
          }
        }
      } else if (action.lang === 'EN') {
        console.log('aaa')
        state = {
          ...state,
          lang: {
            ...langEN
          }
        }
      }
      save(state)
      window.location.reload(true)
      return state
    case 'ui':
      state = {
        ...state,
        ui: {
          ...action.ui
        }
      }
      return state
    default:
      return state
  }
}

let store = createStore(dispatch)
window.store = store
export default store
